<style rel="stylesheet/scss" lang="scss" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>

<template>
    <div>
        <div class="container">
            <el-card shadow="hover" style="padding:0">

                <el-form ref="searchForm" :inline="true" :model="searchForm" size="medium" label-width="120px">
                    <el-card class="operate_container" shadow="never">
                        <div class="wrapper">
                            <div><i class="el-icon-tickets" style="margin-right: 10px;"></i>数据列表</div>

                            <!-- 操作按钮 -->
                            <div>
                                <el-button type="primary" icon="el-icon-plus" size="medium" circle @click="addOrUpdateVisible"></el-button>
                                <el-button type="danger" icon="el-icon-delete" size="medium" circle @click="handleBatchDelete"></el-button>
                                <el-button type="primary" icon="el-icon-refresh" size="medium" circle @click="handleResetSearch('searchForm')"></el-button>
                            </div>
                        </div>
                    </el-card>
                </el-form>

                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-card shadow="hover" style="padding:0">
                            <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable size="medium"></el-input>
                            <el-tree
                                v-loading="dataListLoading"
                                show-checkbox
                                node-key="id"
                                ref="categorys"
                                :data="dataList"
                                :props="defaultProps"
                                :expand-on-click-node="false"
                                :filter-node-method="filterNode"
                                @node-click="handleNodeClick">
                                <span class="custom-tree-node" slot-scope="{ node, data }">
                                    <span>{{ node.label }}</span>
                                    <span>
                                        <el-button :disabled="node.level > 2" type="text" size="mini" @click="() => append(data)">添加</el-button>
                                        <el-button type="text" size="mini" @click="() => edit(data)">编辑</el-button>
                                        <el-button :disabled="!node.childNodes.length==0" type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
                                    </span>
                                </span>
                            </el-tree>
                        </el-card>
                    </el-col>

                    <el-col :span="14">
                        <el-table
                            ref="table" size="small" empty-text="暂无数据"
                            element-loading-text="给我一点时间"
                            fit stripe border highlight-current-row
                            :data="info"
                            :header-cell-style="{'padding-top': '10px', 'height': '50px', 'color': '#515A6E', 'background-color': '#f8f8f9'}"
                            @selection-change="handleSelection">
                            <el-table-column label="分类名称" prop="name" width="200"/>
                            <el-table-column label="层级" prop="cateLevel" align="center"/>
                            <el-table-column label="显示" width="80px" align="center">
                                <template slot-scope="scope">
                                    <el-tag type="success" size="small" v-if="scope.row.showStatus === 0">正常</el-tag>
                                    <el-tag type="success" size="small" v-else-if="scope.row.showStatus === 1">正常</el-tag>
                                    <el-tag type="danger" size="small" v-else>未知</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="排序" prop="sort" align="center"/>
                            <el-table-column label="图标地址" prop="icon" align="center"/>
                            <el-table-column label="计量单位" prop="productUnit" align="center"/>
                            <el-table-column label="商品数量" prop="productCount" align="center"/>
                            <el-table-column label="更新时间" prop="utime" align="center" width="150"/>

                        </el-table>
                    </el-col>
                </el-row>


                <!-- 窗口 -->
                <el-dialog
                    :title="!form.id ? '新增' : '修改'"
                    :visible.sync="visible" :close-on-click-modal="false" @close="handleDialogClose">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                        <el-form-item label="分类名称" prop="name">
                            <el-input v-model="form.name" placeholder="分类名称" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="是否显示" prop="showStatus">
                            <el-radio-group v-model="form.showStatus">
                                <el-radio :label="1" border>显示</el-radio>
                                <el-radio :label="0" border>不显示</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="排序" prop="sort">
                            <el-input-number v-model="form.sort" :min="1" :max="10000" placeholder="排序" style="width: 80%;"></el-input-number>
                        </el-form-item>
                        <el-form-item label="图标地址" prop="icon">
                            <el-input v-model="form.icon" placeholder="图标地址" style="width: 80%;"></el-input>
                        </el-form-item>
                        <el-form-item label="计量单位" prop="productUnit">
                            <el-input v-model="form.productUnit" placeholder="计量单位" style="width: 80%;"></el-input>
                        </el-form-item>

                    </el-form>

                    <div slot="footer" class="dialog-footer">
                        <el-button @click="visible = false">取 消</el-button>
                        <el-button @click="handleSubmit('form')" type="primary" :loading="submitLoading">提 交</el-button>
                    </div>
                </el-dialog>
            </el-card>
        </div>
    </div>
</template>

<script>
import { save, deleted, updated, info, list, page, selectMyPage, listTree } from "@/api/product/pmscategory"

export default {
    data() {
        return {
            visible: false,
            submitLoading: false,

            dataList: [],
            dataListLoading: true,
            selectionRows: [],

            searchForm: {
                keyword: null,
            },
            form: {
                id: null,
                pid: null,
                name: null,
                cateLevel: null,
                showStatus: 1,
                sort: null,
                icon: null,
                productUnit: null,
                productCount: null,
                ctime: null,
                utime: null
            },
            rules: {
                name: [
                    { required: true, message: '分类名称不能为空', trigger: 'blur' }
                ]
            },

            defaultProps: {
                label: 'name',
                children: 'children'
            },
            filterText: "",

            info: []
        }
    },
    mounted() {
    	this.$nextTick(function () {
	        this.getDataList()
    	})
    },
    //监控data中的数据变化
    watch: {
        filterText(val) {
        this.$refs.categorys.filter(val);
        }
    },
    methods: {
        /**
         * 树节点过滤
         */
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        /**
         * 获取节点详情
         */
        handleNodeClick(data, node, e) {
            this.info = [data]
        },
        append(data) {
            this.form.pid = data.id;
            this.form.cateLevel = data.cateLevel * 1 + 1;
            this.addOrUpdateVisible(null);
        },
        edit(data) {
            this.addOrUpdateVisible(data);
        },
        remove(node, data) {
            this.handleDelete(data)
        },
        
        handleSelection(selection) { // 多选
            this.selectionRows = selection
        },
        handleSizeChange(val) { // 每页数量
            this.searchForm.limit = val
            this.getDataList()
        },
        handleCurrentChange(val) { // 页码
            this.searchForm.page = val
            this.getDataList()
        },
        handleResetSearch(name) { // 重置搜索表单
            this.handleReset(name)
            this.getDataList()
        },
        handleReset(name) { // 重置表单
            const refs = this.$refs
            refs[name].resetFields()
        },
        handleSearch() { // 单条件搜索
            this.getDataList()
        },
        handleDialogClose() { //表单窗口关闭
            this.handleReset('form')
            this.form.pid = null;
            this.form.cateLevel = null;
        },

		/**
         * 打开表单窗口
         */
		addOrUpdateVisible(data) {
            this.visible = true
            if (data && data.id) {
                this.getInfo(data.id).then(res => {
                    this.form = Object.assign({}, res.data)
                })
            } else {
                this.form.id = null
                if(!this.form.pid) {
                    this.form.pid = 0
                    this.form.cateLevel = 1;
                }
            }
        },

		/**
         * 提交表单
         */
        handleSubmit(name) {
        	const refs = this.$refs
            refs[name].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    if (!this.form.id) {
                        save(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else if (this.form.id) {
                        updated(this.form).then(res => {
                            if (this.ResultMessage(res)) {
                                this.submitLoading = false
                                this.visible = false
                                this.handleReset('form')
                                this.getDataList()
                            } else {
                                this.submitLoading = false
                            }
                        }).catch(error => {
                            this.submitLoading = false
                            this.$notify({ title: '错误', message: error, type: 'error' });
                        })
                    } else {
                        console.log('未知操作');
                    }
                }
            })
        },
		
		/**
         * 删除
         */
        handleDelete(row) { 
            let ids = []
            if (row.id != undefined) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {    
                this.$confirm('确定要删除？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
                    deleted(ids).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {})
            }
        },

        /**
         * 批量删除
         */
        handleBatchDelete() {
            let cateIds = [];
            let checkedNodes = this.$refs.categorys.getCheckedNodes();
            
            if(checkedNodes.length > 0) {
                for (let i = 0; i < checkedNodes.length; i++) {
                    cateIds.push(checkedNodes[i].id);
                }
                this.$confirm(`是否批量删除菜单?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    deleted(cateIds).then(res => {
                        if (this.ResultMessage(res)) {
                            this.getDataList()
                        } 
                    }).catch(error => {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    })
                }).catch(() => {});
            } else {
                this.$notify({ title: '提示', message: '请选择需要删除的数据', type: 'warning' });
            }
        },

		/**
         * 详细信息
         */
        getInfo(id) {
            if (id !== undefined) {
                return info(id).then(res => {
                    if (this.ResultMessage(res, false)) {
                        return res
                    } else {
                        this.$notify({ title: '错误', message: error, type: 'error' });
                    }
                }).catch(error => {
                    this.$notify({ title: '错误', message: error, type: 'error' });
                })
            }
        },
		
        /**
         * 数据列表
         */
        getDataList() {
            listTree().then(res => {
                if (this.ResultMessage(res, false)) {
                    this.dataList = res.data
                    this.dataListLoading = false
                } else {
                    this.dataListLoading = false
                }
            }).catch(error => {
                this.dataListLoading = false
                this.$notify({ title: '错误', message: error, type: 'error' });
            })
        }
    }
}
</script>